<template>
  <div>
    <div ref="container" id="container"></div>
  </div>
</template>

<script setup>
import { MMDAnimationHelper } from "three/examples/jsm/animation/MMDAnimationHelper.js";
import { MMDLoader } from "three/examples/jsm/loaders/MMDLoader.js";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
import * as THREE from "three";
import { onMounted, reactive, ref, onUnmounted } from "vue";

const container = ref(null);

let scene, camera, renderer, clock;
let frameId;
// 创建全局变量以便在键盘事件中访问
let helper;
let modelMesh;
let loader;
let currentAnimation = 'tw'; // 跟踪当前播放的动画

// 存储模型的初始状态
let originalModelState = null;
let initialModelLoaded = false;

// 处理键盘事件的函数
function handleKeyDown(event) {
  if (!initialModelLoaded) return;
  
  if (event.key.toLowerCase() === 'a') {
    if (currentAnimation !== 'ayaka-dance') {
      loadAnimation('/move/ayaka-dance.vmd');
      currentAnimation = 'ayaka-dance';
    }
  } else if (event.key.toLowerCase() === 'b') {
    if (currentAnimation !== 'tw') {
      loadAnimation('/move/tw.vmd');
      currentAnimation = 'tw';
    }
  }
}

// 加载新动画的函数
function loadAnimation(animationPath) {
  // 从场景中移除当前模型
  if (modelMesh) {
    // 首先从helper中移除模型
    if (helper) {
      helper.remove(modelMesh);
    }
    scene.remove(modelMesh);
  }
  
  // 创建新的helper实例
  helper = new MMDAnimationHelper();
  
  // 重新加载模型和动画
  loader.loadWithAnimation(
    "/qque/青雀（分桦）.pmx",
    animationPath,
    function onLoad(mmd) {
      modelMesh = mmd.mesh;
      
      helper.add(mmd.mesh, {
        animation: mmd.animation,
        physics: true
      });

      scene.add(mmd.mesh);
    },
    onProgress,
    function(error) {
      console.error('加载模型或动画出错:', error);
    }
  );
}

function onProgress(xhr) {
  if (xhr.lengthComputable) {
    const percentComplete = xhr.loaded / xhr.total * 100;
    console.log(Math.round(percentComplete) + '% 已下载');
  }
}

onMounted(() => {
  // 相机位置的响应式数据
  const cameraPosition = reactive({
    x: 0,
    y: 0,
    z: 75,
  });
  const width = window.innerWidth;
  const height = window.innerHeight;
  scene = new THREE.Scene();
  camera = new THREE.PerspectiveCamera(750, width / height, 0.1, 2000);
  loader = new MMDLoader();
  const light = new THREE.AmbientLight(0xa0a0a0);
  scene.add(light);

  camera.position.set(cameraPosition.x, cameraPosition.y, cameraPosition.z);

  helper = new MMDAnimationHelper();
  
  // 在这里加载初始模型和动画
  loader.loadWithAnimation(
    "/qque/青雀（分桦）.pmx",
    "/move/tw.vmd",
    function onLoad(mmd) {
      modelMesh = mmd.mesh;
      initialModelLoaded = true;
      
      helper.add(mmd.mesh, {
        animation: mmd.animation,
        physics: true
      });

      scene.add(mmd.mesh);
    },
    onProgress,
    function(error) {
      console.error('加载初始模型或动画出错:', error);
    }
  );

  renderer = new THREE.WebGLRenderer({ antialias: true, alpha: false });
  renderer.setSize(width, height);
  renderer.setClearColor(new THREE.Color(0x000000));
  clock = new THREE.Clock();

  container.value.appendChild(renderer.domElement);

  const controls = new OrbitControls(camera, renderer.domElement);
  controls.target.set(0, 10, 0);
  controls.update();

  // 创建地平面的几何体
  const planeGeometry = new THREE.PlaneGeometry(40, 40); // 宽度和高度为40个单位
  const planeMaterial = new THREE.MeshBasicMaterial({ color: 0x001100 });
  const planeMesh = new THREE.Mesh(planeGeometry, planeMaterial);

  // 将地平面旋转90度，使其水平
  planeMesh.rotation.x = -Math.PI / 2;

  scene.add(planeMesh);

  function render() {
    helper.update(clock.getDelta());
    renderer.render(scene, camera);
    frameId = requestAnimationFrame(render);
  }

  controls.addEventListener("change", render);

  // 添加键盘事件监听器
  window.addEventListener('keydown', handleKeyDown);

  render();
});

onUnmounted(() => {
  cancelAnimationFrame(frameId);
  // 移除键盘事件监听器
  window.removeEventListener('keydown', handleKeyDown);
});
</script>
